//
//  RABleServiceController.m
//  RayoSmartBleKey
//
//  Created by Piccolo on 2017/7/13.
//  Copyright © 2017年 Piccolo. All rights reserved.
//

#import "RABleServiceController.h"



@interface RABleServiceController () {
    id _babyDelegateBuffer;
}


//@property  (atomic, copy) NSMutableArray *locksUnlockEventArray;
//@property  (atomic, copy) NSTimer *locksEventTimer;
@property (nonatomic, strong) CBCentralManager *manager;
@property (nonatomic, assign) BOOL isScanning;

@end

@implementation RABleServiceController

//实现单例方法
+ (instancetype)sharedManager{
    
    static RABleServiceController *tool = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        tool = [[self alloc] init];
    });
//    [SetKeyController setDelegate:tool];
    return tool;

}

- (void)initBleServiceWithDelegate:(id)delegate{
    RABleServiceController.sharedManager.delegate = delegate;
    if (!self.manager) {
//    if (YES) {

//        self.manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
        #if  __IPHONE_OS_VERSION_MIN_REQUIRED > __IPHONE_6_0
                NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                                         //蓝牙power没打开时alert提示框
                                         [NSNumber numberWithBool:YES],CBCentralManagerOptionShowPowerAlertKey,
                                         //重设centralManager恢复的IdentifierKey
                                         @"babyBluetoothRestore",CBCentralManagerOptionRestoreIdentifierKey,
                                         nil];
        #else
                NSDictionary *options = nil;
        #endif
                NSArray *backgroundModes = [[[NSBundle mainBundle] infoDictionary]objectForKey:@"UIBackgroundModes"];
                if ([backgroundModes containsObject:@"bluetooth-central"]) {
                    //后台模式
                    self.manager = [[CBCentralManager alloc]initWithDelegate:self queue:nil options:options];
                }
                else {
                    //非后台模式
                    self.manager = [[CBCentralManager alloc]initWithDelegate:self queue:nil];
                }
    }

}

- (void)startScanBle {
    
    _manager.delegate = self;
    //#68bsc
    if ([RASystemServicePermission bluetoothServiceAvailable]) {
        if (_peripheral){
            [self disconnectBle];
        }
        if (DEVICE_VERSION >= 9 ? ![_manager isScanning] : YES){
            //扫描外设备(第一个参数为nil就是扫描所有的设备)
            [_manager scanForPeripheralsWithServices:nil options:nil];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kScanDurationTime * NSEC_PER_SEC)), dispatch_get_global_queue(0, 0), ^{
                [_manager stopScan];
            });
        } else {
            [_manager stopScan];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self startScanBle];
            });
        }
    } else {
        [RAUtil showAlertViewWithPermissionType:NSRAPermissionTypeBlueTooth viewController:[RAUtil getTopMostViewController]];
    }
    
}

- (void)stopScan{
    if (_peripheral){
//        [self disconnectBle];
//        _peripheral = nil;
    }
    [_manager stopScan];
}


- (void)disconnectBle{
    
    if (_peripheral) {
        [_manager cancelPeripheralConnection:_peripheral];
//        [RASimpleFSUSDK disConnectBle];

    }
//    [RASimpleFSUSDK disConnectBle];
    //断开连接;
    
}

- (CBPeripheralState)currentBleState{
    return self.peripheral.state;
}

#pragma mark - RASimpleFSUSDK function

- (void)initSimpleFSUSDK{
    
    [RASimpleFSUSDK setDelegate:self];
    [RASimpleFSUSDK initBlueToothManagerWithManager:_manager];
    if (!_babyDelegateBuffer) {
        _babyDelegateBuffer = _manager.delegate;
    }
    _manager.delegate = _babyDelegateBuffer;
    [RASimpleFSUSDK initSDK];
}

#pragma mark -RAGeneralFSUSDK function

- (void)initGeneralFSUSDK {
    
    [RAGeneralFSUSDK setDelegate:self];
    [RAGeneralFSUSDK initBlueToothManagerWithManager:_manager];
    if (!_babyDelegateBuffer) {
        _babyDelegateBuffer = _manager.delegate;
    }
    _manager.delegate = _babyDelegateBuffer;
    [RAGeneralFSUSDK initSDK];
}

#pragma mark - CBCentralManagerDelegate

- (void)centralManagerDidUpdateState:(CBCentralManager *)central{
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:
            _bluetoothIsOn = YES;
            break;
        case CBCentralManagerStatePoweredOff:
            _bluetoothIsOn = NO;
//            [RAUtil showAlertViewWithTitle:[RAUtil getSingleKeyStr:@"TEXT_CHECK_BLUETOOTH"] message:nil delegate:self];
            [RAUtil showAlertViewWithPermissionType:NSRAPermissionTypeBlueTooth viewController:[RAUtil getTopMostViewController]];
            break;
        default:
            break;
    }

}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *, id> *)advertisementData RSSI:(NSNumber *)RSSI{
    NSLog(@"@157:peripheral:%@---name:%@", peripheral, peripheral.name);
    NSString *gapName = peripheral.name;
    NSString *identityName = [advertisementData objectForKey:CBAdvertisementDataLocalNameKey];
    NSString *peripheralName = gapName;
    if (identityName && ![identityName isEqualToString:@""] && ![gapName isEqualToString:identityName]) {
        peripheralName = identityName;
    }
    
    if ([RAUtil delegateExist:RABleServiceController.sharedManager.delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(scanedPeripheral:peripheralName:RSSI:)]){
        [RABleServiceController.sharedManager.delegate scanedPeripheral:peripheral peripheralName:peripheralName RSSI:RSSI];
    }
}

- (void)cancelPeripheralConnection:(CBPeripheral *)peripheral{
    
}


#pragma mark - RASimpleFSUSDKDelegate

- (void)currentFSURssi:(NSNumber *)rssi{
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(currentFSURssi:)]) {
        [_delegate currentFSURssi:rssi];
    }
}

- (void)simpleFsuRequestInitSdkResultInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestInitSdkResultInfo:)]) {
        [_delegate simpleFsuRequestInitSdkResultInfo:info];
    }
}

- (void)simpleFsuRequestDestroyResultInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestDestroyResultInfo:)]) {
        [_delegate simpleFsuRequestDestroyResultInfo:info];
    }
}

- (void)simpleFsuRequestConnectResultInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestConnectResultInfo:)]) {
        [_delegate simpleFsuRequestConnectResultInfo:info];
    }
}

- (void)simpleFsuRequestDisconnectResultInfo:(RAFSUSDKResultInfo *)info {
    
    [self disconnectBle];
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestDisconnectResultInfo:)]) {
        [_delegate simpleFsuRequestDisconnectResultInfo:info];
    }
}

- (void)simpleFsuRequestSetOnlineOpenResultInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestSetOnlineOpenResultInfo:)]) {
        [_delegate simpleFsuRequestSetOnlineOpenResultInfo:info];
    }
}

- (void)simpleFsuRequestSetFsuTimeResultInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestSetFsuTimeResultInfo:)]) {
        [_delegate simpleFsuRequestSetFsuTimeResultInfo:info];
    }
}

- (void)simpleFsuRequestActiveReport:(RAFSUSDKActiveReportInfo *)fsuActiveReportInfo{
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestActiveReport:)]) {
        [_delegate simpleFsuRequestActiveReport:fsuActiveReportInfo];
    }
}

- (void)simpleFsuRequestReadFSUEvent:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestReadFSUEvent:)]) {
        [_delegate simpleFsuRequestReadFSUEvent:info];
    }
}

- (void)simpleFsuRequestCleanFSUEvent:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestCleanFSUEvent:)]) {
        [_delegate simpleFsuRequestCleanFSUEvent:info];
    }
}

- (void)simpleFsuRequestReadFSUDeviceID:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestReadFSUDeviceID:)]) {
        [_delegate simpleFsuRequestReadFSUDeviceID:info];
    }
}

- (void)simpleFsuRequestSetFSUDeviceID:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestSetFSUDeviceID:)]) {
        [_delegate simpleFsuRequestSetFSUDeviceID:info];
    }
}

- (void)simpleFsuRequestGetFSUServiceInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestGetFSUServiceInfo:)]) {
        [_delegate simpleFsuRequestGetFSUServiceInfo:info];
    }
}

- (void)simpleFsuRequestSetFSUServiceInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestSetFSUServiceInfo:)]) {
        [_delegate simpleFsuRequestSetFSUServiceInfo:info];
    }
}

- (void)simpleFsuRequestGetFSUWirelessInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestGetFSUWirelessInfo:)]) {
        [_delegate simpleFsuRequestGetFSUWirelessInfo:info];
    }
}

- (void)simpleFsuRequestSetFSUWirelessInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestSetFSUWirelessInfo:)]) {
        [_delegate simpleFsuRequestSetFSUWirelessInfo:info];
    }
}

- (void)simpleFsuRequestGetPPPAddressInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestGetPPPAddressInfo:)]) {
        [_delegate simpleFsuRequestGetPPPAddressInfo:info];
    }
}

- (void)simpleFsuRequestReadSimCardInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestReadSimCardInfo:)]) {
        [_delegate simpleFsuRequestReadSimCardInfo:info];
    }
}

- (void)simpleFsuRequestReadThresholdInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestReadThresholdInfo:)]) {
        [_delegate simpleFsuRequestReadThresholdInfo:info];
    }
}

- (void)simpleFsuRequestSetThresholdInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestSetThresholdInfo:)]) {
        [_delegate simpleFsuRequestSetThresholdInfo:info];
    }
}

- (void)simpleFsuRequestReadFSUMacAndVerson:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestReadFSUMacAndVerson:)]) {
        [_delegate simpleFsuRequestReadFSUMacAndVerson:info];
    }
}

- (void)simpleFsuRequestReadFSUUnvarnishedTransmissionInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(simpleFsuRequestReadFSUUnvarnishedTransmissionInfo:)]) {
        [_delegate simpleFsuRequestReadFSUUnvarnishedTransmissionInfo:info];
    }
}

#pragma mark - RAGeneralFSUSDKDelegate

- (void)generalFsuRequestInitSdkResultInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestInitSdkResultInfo:)]) {
        [_delegate generalFsuRequestInitSdkResultInfo:info];
    }
}

- (void)generalFsuRequestDestroyResultInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestDestroyResultInfo:)]) {
        [_delegate generalFsuRequestDestroyResultInfo:info];
    }
}

- (void)generalFsuRequestConnectResultInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestConnectResultInfo:)]) {
        [_delegate generalFsuRequestConnectResultInfo:info];
    }
}

- (void)generalFsuRequestDisconnectResultInfo:(RAFSUSDKResultInfo *)info {
    
    [self disconnectBle];
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestDisconnectResultInfo:)]) {
        [_delegate generalFsuRequestDisconnectResultInfo:info];
    }
}


- (void)generalFsuRequestReadFSUDeviceID:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestReadFSUDeviceID:)]) {
        [_delegate generalFsuRequestReadFSUDeviceID:info];
    }
}

- (void)generalFsuRequestGetFSUServiceInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestGetFSUServiceInfo:)]) {
        [_delegate generalFsuRequestGetFSUServiceInfo:info];
    }
}

- (void)generalFsuRequestSetFSUServiceInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestSetFSUServiceInfo:)]) {
        [_delegate generalFsuRequestSetFSUServiceInfo:info];
    }
}

- (void)generalFsuRequestGetFSUWirelessInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestGetFSUWirelessInfo:)]) {
        [_delegate generalFsuRequestGetFSUWirelessInfo:info];
    }
}

- (void)generalFsuRequestSetFSUWirelessInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestSetFSUWirelessInfo:)]) {
        [_delegate generalFsuRequestSetFSUWirelessInfo:info];
    }
}

- (void)generalFsuRequestGetPPPAddressInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestGetPPPAddressInfo:)]) {
        [_delegate generalFsuRequestGetPPPAddressInfo:info];
    }
}

- (void)generalFsuRequestSetfsuEthernetParameterInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestSetfsuEthernetParameterInfo:)]) {
        [_delegate generalFsuRequestSetfsuEthernetParameterInfo:info];
    }
}

- (void)generalFsuRequestGetfsuEthernetParameterInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestGetfsuEthernetParameterInfo:)]) {
        [_delegate generalFsuRequestGetfsuEthernetParameterInfo:info];
    }
}

- (void)generalFsuRequestGetfsuHeartBeatInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestGetfsuHeartBeatInfo:)]) {
        [_delegate generalFsuRequestGetfsuHeartBeatInfo:info];
    }
}

- (void)generalFsuRequestSetTimeInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestSetTimeInfo:)]) {
        [_delegate generalFsuRequestSetTimeInfo:info];
    }
}

- (void)generalFsuRequestGetTimeInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestGetTimeInfo:)]) {
        [_delegate generalFsuRequestGetTimeInfo:info];
    }
}

- (void)generalFsuRequestSetMotorActionInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestSetMotorActionInfo:)]) {
        [_delegate generalFsuRequestSetMotorActionInfo:info];
    }
}

- (void)generalFsuRequestGetMotorActionInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestGetMotorActionInfo:)]) {
        [_delegate generalFsuRequestGetMotorActionInfo:info];
    }
}

- (void)generalFsuRequestSetDoParameterInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestSetDoParameterInfo:)]) {
        [_delegate generalFsuRequestSetDoParameterInfo:info];
    }
}

- (void)generalFsuRequestGetDoParameterInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestGetDoParameterInfo:)]) {
        [_delegate generalFsuRequestGetDoParameterInfo:info];
    }
}

- (void)generalFsuRequestSetDoActionInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestSetDoActionInfo:)]) {
        [_delegate generalFsuRequestSetDoActionInfo:info];
    }
}

- (void)generalFsuRequestSetSystemUpdateInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestSetSystemUpdateInfo:)]) {
        [_delegate generalFsuRequestSetSystemUpdateInfo:info];
    }
}

- (void)generalFsuRequestSetRestartInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestSetRestartInfo:)]) {
        [_delegate generalFsuRequestSetRestartInfo:info];
    }
}

- (void)generalFsuRequestSetResetInfo:(RAFSUSDKResultInfo *)info {
    
    if ([RAUtil delegateExist:_delegate delegate:@protocol(RABleServiceControllerDelegate) selector:@selector(generalFsuRequestSetResetInfo:)]) {
        [_delegate generalFsuRequestSetResetInfo:info];
    }
}

- (BOOL)isScanning {
    
    if (@available(iOS 9.0, *)) {
        return _manager.isScanning;
    } else {
        return NO;
        // Fallback on earlier versions
    }
}
@end

